{% load static %} {% load custom_filters %}
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>{% if form.instance.id %}编辑{% else %}新增{% endif %}数据源 - 数据源管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" />
    <style>
      :root {
        --primary-color: #0d6efd;
        --success-color: #198754;
        --danger-color: #dc3545;
        --warning-color: #ffc107;
        --info-color: #0dcaf0;
      }

      body {
        background-color: #f8f9fa;
      }

      .sidebar {
        height: 100vh;
        background: linear-gradient(135deg, #343a40 0%, #495057 100%);
        color: white;
        padding-top: 20px;
        box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
      }

      .sidebar .nav-link {
        color: #adb5bd;
        border-radius: 8px;
        margin: 2px 8px;
        transition: all 0.3s ease;
      }

      .sidebar .nav-link:hover {
        background-color: rgba(255, 255, 255, 0.1);
        color: white;
        transform: translateX(5px);
      }

      .sidebar .nav-link.active {
        background: linear-gradient(135deg, var(--primary-color), #0b5ed7);
        color: white;
        box-shadow: 0 4px 8px rgba(13, 110, 253, 0.3);
      }

      .content {
        padding: 20px;
      }

      .card {
        border: none;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        border-radius: 12px;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
      }

      .card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 15px rgba(0, 0, 0, 0.15);
      }

      .card-header {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        border-radius: 12px 12px 0 0 !important;
        font-weight: 600;
      }

      .form-group {
        margin-bottom: 1.5rem;
      }

      .form-control,
      .form-select {
        border-radius: 8px;
        border: 1px solid #dee2e6;
        transition: all 0.3s ease;
      }

      .form-control:focus,
      .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
        transform: translateY(-1px);
      }

      .form-control.is-invalid {
        border-color: var(--danger-color);
        box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
      }

      .required-mark {
        color: var(--danger-color);
      }

      #connectionResult {
        max-width: 100%;
        margin: 1rem 0;
        animation: slideIn 0.3s ease;
      }

      @keyframes slideIn {
        from {
          opacity: 0;
          transform: translateY(-10px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }

      .btn {
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;
      }

      .btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      }

      .btn:active {
        transform: translateY(0);
      }

      .btn:disabled {
        transform: none;
        box-shadow: none;
      }

      .navbar {
        border-radius: 12px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 1.5rem;
      }

      @media (max-width: 768px) {
        .content {
          padding: 15px;
        }

        .card {
          margin-bottom: 1rem;
        }
      }
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-2 d-none d-md-block sidebar">
          <div class="text-center mb-4">
            <h3>数据管理</h3>
          </div>
          <ul class="nav flex-column">
            <li class="nav-item">
              <a class="nav-link" href="{% url 'datasource_list' %}">
                <i class="bi bi-database me-2"></i>
                数据源管理
              </a>
            </li>
            <!-- <li class="nav-item">
              <a class="nav-link" href="{% url 'agent_management' %}">
                <i class="bi bi-robot me-2"></i>
                智能体管理
              </a>
            </li> -->
            <li class="nav-item">
              <a class="nav-link" href="{% url 'operation_log' %}">
                <i class="bi bi-clock-history me-2"></i>
                操作日志
              </a>
            </li>
          </ul>
        </div>

        <!-- 主内容区 -->
        <main class="col-md-10 ms-sm-auto px-md-4 content">
          <!-- 顶部导航 -->
          <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
            <div class="container-fluid">
              <a href="{% url 'datasource_list' %}" class="btn btn-outline-secondary me-2">
                <i class="bi bi-arrow-left me-1"></i>
                返回
              </a>
              <h4 class="mb-0">{% if form.instance.id %}编辑{% else %}新增{% endif %}数据源</h4>
              <div class="d-flex ms-auto">
                <button class="btn btn-outline-secondary me-2">
                  <i class="bi bi-person me-1"></i>
                  登录
                </button>
              </div>
            </div>
          </nav>

          <!-- 表单卡片 -->
          <div class="card">
            <div class="card-header">
              <h5 class="mb-0">数据源基本信息</h5>
            </div>
            <div class="card-body">
              <form method="post" {% if form.instance.id %}action="{% url 'datasource_edit' form.instance.id %}" {% else %}action="{% url 'datasource_create' %}" {% endif %} novalidate>
                {% csrf_token %}
                <!-- 隐藏字段：仅编辑时存在，记录当前数据源ID -->
                {% if form.instance.id %}
                <input type="hidden" name="id" value="{{ form.instance.id }}" />
                {% endif %}
                <!-- 基本信息区域 -->
                <div class="row mb-4">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="{{ form.name.id_for_label }}">
                        名称
                        <span class="required-mark">*</span>
                      </label>
                      {{ form.name|add_class:"form-control" }} {% if form.name.errors %}
                      <div class="invalid-feedback d-block">{{ form.name.errors.0 }}</div>
                      {% endif %}
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="{{ form.description.id_for_label }}">描述</label>
                      {{ form.description|add_class:"form-control" }}
                    </div>
                  </div>
                </div>

                <!-- 数据库连接信息区域 -->
                <div class="card mb-4">
                  <div class="card-header">
                    <h5 class="mb-0">数据库连接信息</h5>
                  </div>
                  <div class="card-body">
                    <div class="row">
                      <div class="col-md-6">
                        <div class="form-group">
                          <label for="{{ form.engine.id_for_label }}">
                            数据库类型
                            <span class="required-mark">*</span>
                          </label>
                          {{ form.engine|add_class:"form-select" }} {% if form.engine.errors %}
                          <div class="invalid-feedback d-block">{{ form.engine.errors.0 }}</div>
                          {% endif %}
                        </div>
                      </div>
                      <div class="col-md-6">
                        <div class="form-group">
                          <label for="{{ form.host.id_for_label }}">
                            主机
                            <span class="required-mark">*</span>
                          </label>
                          {{ form.host|add_class:"form-control" }} {% if form.host.errors %}
                          <div class="invalid-feedback d-block">{{ form.host.errors.0 }}</div>
                          {% endif %}
                        </div>
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-md-6">
                        <div class="form-group">
                          <label for="{{ form.port.id_for_label }}">
                            端口
                            <span class="required-mark">*</span>
                          </label>
                          {{ form.port|add_class:"form-control" }} {% if form.port.errors %}
                          <div class="invalid-feedback d-block">{{ form.port.errors.0 }}</div>
                          {% endif %}
                        </div>
                      </div>
                      <div class="col-md-6">
                        <div class="form-group">
                          <label for="{{ form.database.id_for_label }}">
                            数据库名
                            <span class="required-mark">*</span>
                          </label>
                          {{ form.database|add_class:"form-control" }} {% if form.database.errors %}
                          <div class="invalid-feedback d-block">{{ form.database.errors.0 }}</div>
                          {% endif %}
                        </div>
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-md-6">
                        <div class="form-group">
                          <label for="{{ form.user.id_for_label }}">
                            用户名
                            <span class="required-mark">*</span>
                          </label>
                          {{ form.user|add_class:"form-control" }} {% if form.user.errors %}
                          <div class="invalid-feedback d-block">{{ form.user.errors.0 }}</div>
                          {% endif %}
                        </div>
                      </div>
                      <div class="col-md-6">
                        <div class="form-group">
                          <label for="{{ form.password.id_for_label }}">密码</label>
                          {{ form.password|add_class:"form-control" }} {% if form.password.errors %}
                          <div class="invalid-feedback d-block">{{ form.password.errors.0 }}</div>
                          {% endif %}
                        </div>
                      </div>
                    </div>

                    <div class="mt-2">
                      <label class="form-label">连接状态</label>
                      <div>
                        <span id="connectionStatus" class="badge {% if form.instance.connection_status %}bg-success{% else %}bg-secondary{% endif %}">
                          {% if form.instance.connection_status %}已连接{% else %}未连接{% endif %}
                        </span>
                        {% if form.instance.connection_status %}
                        <span id="tableCountDisplay" class="badge bg-info ms-2">
                          <i class="bi bi-table"></i>
                          <span id="tableCountValue">{{ form.instance.table_count }}</span>
                          个表
                        </span>
                        {% else %}
                        <span id="tableCountDisplay" class="badge bg-info ms-2" style="display: none">
                          <i class="bi bi-table"></i>
                          <span id="tableCountValue">0</span>
                          个表
                        </span>
                        {% endif %}
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 操作按钮（在原有保存/取消按钮上方添加测试按钮） -->
                <div class="d-flex justify-content-end gap-2 mb-3">
                  <button type="button" id="testConnectionBtn" class="btn btn-info">
                    <i class="bi bi-plug me-1"></i>
                    测试连接
                  </button>
                </div>

                <!-- 操作按钮 -->
                <div class="d-flex justify-content-end gap-2">
                  <a href="{% url 'datasource_list' %}" class="btn btn-outline-secondary">取消</a>
                  <button type="submit" class="btn btn-primary">保存</button>
                </div>
              </form>
            </div>
          </div>
        </main>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>

      document.addEventListener('DOMContentLoaded', function () {
          // 获取测试按钮和表单
          const testBtn = document.getElementById('testConnectionBtn')
          const form = document.querySelector('form')

          // 如果是编辑模式，根据当前状态初始化显示
          {% if form.instance.id %}
          const currentStatus = {{ form.instance.connection_status|yesno:"true,false" }};
          const currentTableCount = {{ form.instance.table_count|default:0 }};
          if (currentStatus) {
            updateConnectionStatus(true, currentTableCount);
          }
          {% endif %}

        // 测试连接按钮点击事件
        testBtn.addEventListener('click', async function () {
          // 清除之前的错误状态
          document.querySelectorAll('.is-invalid').forEach((el) => el.classList.remove('is-invalid'))

          // 1. 收集表单数据
          const formData = new FormData(form)

          // 2. 前端验证必填字段
          const requiredFields = ['engine', 'host', 'port', 'database', 'user']
          let isValid = true

          requiredFields.forEach((field) => {
            const value = formData.get(field)
            if (!value || value.toString().trim() === '') {
              isValid = false
              const fieldEl = document.querySelector(`[name="${field}"]`)
              if (fieldEl) {
                fieldEl.classList.add('is-invalid')
                fieldEl.focus()
              }
            }
          })

          if (!isValid) {
            updateConnectionStatus(false)
            return
          }

          // 验证端口是否为有效数字
          const port = parseInt(formData.get('port'))
          if (isNaN(port) || port <= 0 || port > 65535) {
            const portField = document.querySelector('[name="port"]')
            portField.classList.add('is-invalid')
            portField.focus()
            updateConnectionStatus(false)
            return
          }

          // 3. 发送测试连接请求
          try {
            // 显示加载状态
            testBtn.disabled = true
            testBtn.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i>测试中...'



            // 统一使用测试连接URL
            const url = '{% url "test_connection" %}'

            const response = await fetch(url, {
              method: 'POST',
              body: formData,
              headers: {
                'X-Requested-With': 'XMLHttpRequest'
              }
            })

            if (!response.ok) {
              throw new Error(`HTTP ${response.status}: ${response.statusText}`)
            }

            const data = await response.json()

            // 4. 更新连接状态
            if (data.status === 'success') {
              updateConnectionStatus(true, data.table_count || 0)
            } else {
              updateConnectionStatus(false)
            }
          } catch (error) {
            console.error('测试连接错误：', error)
            updateConnectionStatus(false)
          } finally {
            // 恢复按钮状态
            testBtn.disabled = false
            testBtn.innerHTML = '<i class="bi bi-plug me-1"></i>测试连接'
          }
        })

        // 更新连接状态的函数
        function updateConnectionStatus(connected, tableCount = 0) {
          const statusBadge = document.getElementById('connectionStatus')
          const countDisplay = document.getElementById('tableCountDisplay')
          const countValue = document.getElementById('tableCountValue')

          if (connected) {
            statusBadge.textContent = '已连接'
            statusBadge.className = 'badge bg-success'
            countValue.textContent = tableCount
            countDisplay.style.display = 'inline-block'
          } else {
            statusBadge.textContent = '未连接'
            statusBadge.className = 'badge bg-secondary'
            countDisplay.style.display = 'none'
          }
        }

        // 监听表单字段变化，移除错误状态
        document.querySelectorAll('input, select').forEach((input) => {
          input.addEventListener('input', function () {
            this.classList.remove('is-invalid')
          })
        })
      })
    </script>
  </body>
</html>
